package com.biqee.service.tb.impl;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.log4j.Logger;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.biqee.model.TaobaoShopParseResult;
import com.biqee.service.tb.TaobaoBShopParseService;
import com.biqee.util.JSONUtil;
import com.biqee.util.JsoupUtil;

public class TaobaoBShopParseServiceImpl implements TaobaoBShopParseService {
	private static final Logger logger = Logger.getLogger(TaobaoBShopParseServiceImpl.class);
	
	@Override
	public TaobaoShopParseResult parse(Document doc) {
		if(doc == null) {
			throw new RuntimeException("null document!");
		}
		
		TaobaoShopParseResult result = new TaobaoShopParseResult();
		try {
			Elements divElememts = doc.select("div");
			for(Element element : divElememts) {
				if("J_shopViewed".equals(element.attr("id"))) {
					String dataValue = element.attr("data-value");
										
					Object dataObj = JSONUtil.jsonToObject(dataValue);
					String shopId = (String)PropertyUtils.getProperty( dataObj, "shopId" );
					String name = (String)PropertyUtils.getProperty( dataObj, "name" );
					String link = (String)PropertyUtils.getProperty( dataObj, "link" );
					
					result.setShopId(shopId);
					result.setName(name);
					result.setUrl(link);
					
					break;
				}
			}
						
			Element nickElement = doc.select("span.J_WangWang").first();
			if(nickElement != null) {
				String nick = nickElement.attr("data-nick");
				result.setNick(nick);
			}
			
			Element mallElement = doc.select("span.mlogo").first();
			if(mallElement != null) {
				result.setMallType();
			} else {
				result.setCommonType();
			}
			
			parseGrade(doc, result);

			return result;
		} catch (Exception e) {
			logger.error("parse doc failed. uri: " + doc.baseUri() +
					", cause: ", e);
		}
		
		return null;
	}

	
	/*
	 example:
	 <div class="grade">
		<h4>店铺动态评分</h4>
		<ul>
			<li>
				<span>宝贝与描述相符：</span>
				<a target="_blank" href="http://rate.taobao.com/user-rate-108a12c59e3ae210acefe5481476cd90.htm">
					<span class="c-value-no" title="4.5/5.0，共有12730人打分">
						<i style="width: 4.5em"></i>
					</span>4.5
				</a>
			</li>
			<li>
				<span>卖家的服务态度：</span>
				<a target="_blank" href="http://rate.taobao.com/user-rate-108a12c59e3ae210acefe5481476cd90.htm">
					<span class="c-value-no" title="4.6/5.0，共有12366人打分"><i style="width: 4.6em"></i></span>
					4.6
				</a>
			</li>
			<li>
				<span>卖家发货的速度：</span>
				<a target="_blank" href="http://rate.taobao.com/user-rate-108a12c59e3ae210acefe5481476cd90.htm">
					<span class="c-value-no" title="4.5/5.0，共有12335人打分">
					<i style="width: 4.5em"></i></span>4.5
				</a>
			</li>
		</ul>
	</div>
	 */
	private static final int GRADE_NUM = 3;
	
	private void parseGrade(Document doc, TaobaoShopParseResult result) {
		Element shopGradeElement = doc.select("p.shop-grade").first();
		Element aGradeElement = shopGradeElement.select("a").first();
		result.setFinalGrade(aGradeElement.text());		
		
		Element gradeElement = doc.select("div.grade").first();
		Elements spanElements = gradeElement.select("span.c-value-no");
		if(spanElements.size() != GRADE_NUM) {
			throw new RuntimeException("parse grade failed. element: " + gradeElement);
		}
		
		Element matchGradeElement = spanElements.get(0);
		String matchGrade = getGradeString(matchGradeElement);
		result.setMatchGrade(matchGrade);
		
		Element serviceGradeElement = spanElements.get(1);
		String serviceGrade = getGradeString(serviceGradeElement);
		result.setServiceGrade(serviceGrade);
		
		Element speedGradeElement = spanElements.get(2);
		String speedGrade = getGradeString(speedGradeElement);
		result.setSpeedGrade(speedGrade);
	}
	
	private String getGradeString(Element gradeElement) {
		String gradeString = gradeElement.attr("title");
		int index = gradeString.indexOf("/5.0");
		if(index == -1) {
			throw new RuntimeException("parse grade failed. element: " + gradeElement);
		} else {
			return gradeString.substring(0, index);
		}
	}

	public static void main(String[] args) {
		String filePath = "D:\\work\\biqee\\test-pages\\taobao\\mall\\mall-rate.html";
		InputStream in;
		TaobaoShopParseResult result = null;
		try {
			in = new FileInputStream(filePath);
			TaobaoBShopParseServiceImpl parser = new TaobaoBShopParseServiceImpl();
			Document doc = JsoupUtil.createDocument(in, "gbk", "http://item.taobao.com/item.htm?id=2222538727&traclelog=jubuyoriprice");
			result = parser.parse(doc);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		String desc = ToStringBuilder.reflectionToString(result, ToStringStyle.MULTI_LINE_STYLE);
		System.out.println(desc);
	}
}
